import React, { useState } from 'react';
import { message } from 'antd';
import { CopyOutlined, CheckOutlined } from '@ant-design/icons';
import styles from './index.module.css';

interface CodeBlockProps {
  children: React.ReactNode;
  className?: string;
  language?: string;
}

const CodeBlock: React.FC<CodeBlockProps> = ({ children, className, language }) => {
  const [copied, setCopied] = useState(false);

  // 从className中提取语言信息
  const getLanguage = () => {
    if (language) return language;
    if (className) {
      const match = className.match(/language-(\w+)/);
      return match ? match[1] : '';
    }
    return '';
  };

  const handleCopy = async () => {
    try {
      const codeText = typeof children === 'string' ? children : 
        (children as any)?.props?.children || '';
      
      await navigator.clipboard.writeText(codeText);
      setCopied(true);
      message.success('代码已复制到剪贴板');
      
      setTimeout(() => {
        setCopied(false);
      }, 2000);
    } catch (error) {
      message.error('复制失败');
    }
  };

  const lang = getLanguage();

  return (
    <div className={styles.codeBlockWrapper}>
      <pre 
        className={`${styles.codeBlock} ${className || ''}`}
        data-language={lang}
      >
        <code>{children}</code>
        <button 
          className={styles.copyButton}
          onClick={handleCopy}
          title="复制代码"
        >
          {copied ? <CheckOutlined /> : <CopyOutlined />}
        </button>
      </pre>
    </div>
  );
};

export default CodeBlock; 